import { getToken, setToken, removeToken } from '@/utils/auth'
import { loginAPI, getUserProfile, getUserPhotoAPI } from '@/api'
import router, { resetRouter } from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, myToken) => {
    state.token = myToken
    setToken(myToken)
  },
  // 删除Token
  REMOVE_TOKEN: (state) => {
    state.token = ''
    removeToken()
  },
  // 设置用户名
  SET_USER: (state, value) => {
    state.userInfo = value
  }
}

const actions = {
  // 登录
  async loginActions({ commit }, value) {
    const [err, res] = await loginAPI(value)
    if (!err) commit('SET_TOKEN', res.data)
    return [err, res]
  },
  // 获取用户基本信息和头像
  async getUserInfoActions({ commit }) {
    const res = await getUserProfile()
    const res2 = await getUserPhotoAPI(res.data.userId)
    commit('SET_USER', { ...res.data, ...res2.data })
    console.log(res)
    return res.data.roles.menus
  },
  // 退出登录
  async logOutActions({ commit }) {
    commit('REMOVE_TOKEN')
    commit('RESET_STATE')
    resetRouter() // 重置路由 不重置会报警告 下面的警告
    // [vue-router] Duplicate named routes definition: { name: "Approvals", path: "/approvals/" }
    router.replace(`/login?redirect=${router.currentRoute.fullPath}`)
    console.log(router.currentRoute.fullPath)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
